/**
 * StartFileServiceRegistry.java
 */
package fss;

import java.io.IOException;
import java.rmi.AlreadyBoundException;
import java.rmi.NotBoundException;
import java.rmi.registry.Registry;
import java.util.Scanner;

import fss.remote.FssRegistry;
import fss.util.rmi.RmiId;
import fss.util.rmi.RmiUtils;

/**
 * This is a command line utility to start and stop a Service Registry.
 * <p>
 * No need to have the RMI registry running (i.e. via 'rmiregistry' or
 * a utility clasa). Running this class will start the registry for you.
 * 
 * @author thinh
 *
 */
public class StartFileServiceRegistry {
    private static final String USAGE = "StartRegistry <host> <name>";
    /**
     * @param argsCurrentClient
     * @throws IOException 
     * @throws AlreadyBoundException 
     */
    public static void main(String[] args) throws IOException {
        if(args.length != 2) {
            System.out.println("Error: Invalid number of arguments. Expecting 2.");
            System.out.println("Usage: " + USAGE);
            System.exit(-1);
        }
        Scanner stdin = new Scanner(System.in);
        String host = args[0];
        String name = args[1];
        Integer port = RmiUtils.getAvailableServiceRegistryPort(host);
        
        if(port == null) {
            System.out.println("All dedicated ports for Service Registry objects are used on localhost (" + host + ").");
            System.exit(1);
        }
        
        RmiId id = new RmiId(host, name, port);
        
        FssRegistry fssRegistry = new FssRegistry(id);
        Registry rmi = RmiUtils.exportFssRegistry(fssRegistry);
        fssRegistry.start();
        
        System.out.println("***************************************************************************************");
        System.out.println("Service Registry started " + id + " on port " + port);        
        System.out.println("Hit enter to remove the Service Registry...");
        System.out.println("***************************************************************************************");
        System.out.println();
        stdin.nextLine();
        
        try {
            fssRegistry.stop();
            rmi.unbind(name);
        } catch (NotBoundException e) {
            // ignore
        }
        System.out.println("Service Registry terminated");
        System.exit(0);
    }
}
